package org.dromara.chicken.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.domain.AuditDto;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.chicken.domain.ChickenChickIn;
import org.dromara.chicken.domain.ChickenReduce;
import org.dromara.chicken.domain.ChickenReduceInfo;
import org.dromara.chicken.mapper.ChickenChickInMapper;
import org.dromara.chicken.mapper.ChickenReduceInfoMapper;
import org.dromara.chicken.mapper.ChickenReduceMapper;
import org.dromara.chicken.service.IChickenReduceService;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 减少记录Service业务层处理
 *
 * @author Mr Lei QQ 235921049
 * @date 2024-06-10
 */
@RequiredArgsConstructor
@Service
public class ChickenReduceServiceImpl implements IChickenReduceService {

    private final ChickenReduceMapper baseMapper;
    private final ChickenReduceInfoMapper infoMapper;
    private final ChickenChickInMapper chickInMapper;

    /**
     * 查询减少记录
     */
    @Override
    public ChickenReduce queryById(Long id){
        //查询主表
        ChickenReduce reduce = baseMapper.selectById(id);
        //查询info表
        LambdaQueryWrapper<ChickenReduceInfo> infoWrapper = new LambdaQueryWrapper<>();
        infoWrapper.eq(ChickenReduceInfo::getOrderId,reduce.getId());
//        infoWrapper.eq(ChickenReduceInfo::getOrderTitle,reduce.getTitle());//对接以前旧数据
        List<ChickenReduceInfo> infos = infoMapper.selectList(infoWrapper);
        reduce.setContentInfo(infos);

        return reduce;
    }

    /**
     * 查询减少记录列表
     */
    @Override
    public TableDataInfo<ChickenReduce> queryPageList(ChickenReduce bo, PageQuery pageQuery) {
        Page<ChickenReduce> result = baseMapper.queryPageList(pageQuery.build(), bo);
        return TableDataInfo.build(result);
    }

    /**
     * 查询减少记录列表
     */
    @Override
    public List<ChickenReduce> queryList(ChickenReduce bo) {
        LambdaQueryWrapper<ChickenReduce> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<ChickenReduce> buildQueryWrapper(ChickenReduce bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<ChickenReduce> lqw = Wrappers.lambdaQuery();
        lqw.like(StringUtils.isNotBlank(bo.getTitle()), ChickenReduce::getTitle, bo.getTitle());
        lqw.eq(bo.getAuditStatus() != null, ChickenReduce::getAuditStatus, bo.getAuditStatus());
        return lqw;
    }

    /**
     * 新增减少记录
     */
    @Override
    public Boolean insertByBo(ChickenReduce bo) {
        validEntityBeforeSave(bo);
        boolean flag = baseMapper.insert(bo) > 0;
        if (flag) {
            //主表返回新增ID
            assert bo != null;
            bo.setId(bo.getId());
            //获取子表数据
            List<ChickenReduceInfo> infoList = bo.getContentInfo();
            infoList.forEach(x->{
                //设置子表关联ID
                x.setOrderId(bo.getId());
                x.setRemark(bo.getRemark());
                //执行子表新增方法
                infoMapper.insert(x);
            });
        }
        return flag;
    }

    /**
     * 修改减少记录
     */
    @Override
    public Boolean updateByBo(ChickenReduce bo) {
        validEntityBeforeSave(bo);
        //查询子表
        List<ChickenReduceInfo> infoList = bo.getContentInfo();
        //遍历
        infoList.forEach(v->{
            //设置要修改的关联子表
            v.setOrderId(bo.getId());
            //判断子表中是否有新增，有则执行新增方法
            if(v.getId()==null){
                infoMapper.insert(v);
            }
            //执行子表修改方法
            infoMapper.updateById(v);
        });
        return baseMapper.updateById(bo) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(ChickenReduce entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除减少记录
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        //删除主表同时删除对应的子表
        LambdaQueryWrapper<ChickenReduceInfo> wrapper = new LambdaQueryWrapper<>();
        //主表用id则用wrapper.eq，主表是ids则用wrapper.in
        wrapper.in(ChickenReduceInfo::getOrderId,ids);
        //执行删除子表的方法
        infoMapper.delete(wrapper);
        //执行删除主表的方法
        return baseMapper.deleteBatchIds(ids) > 0;
    }
    /*生成默认标题*/
    @Override
    public String defaultTitle(String formatDate) {
        Integer totalNum = baseMapper.selectByDateCunt(formatDate);
        //最低3位数，不足前面用0填充
        //拼接成新的标题
        return String.format("%03d", totalNum);
    }
/*审核*/
    @Override
    public void updateAudit(AuditDto dto) {
        //创建修改对象
        LambdaUpdateWrapper<ChickenReduce> updateWrapper = new LambdaUpdateWrapper<>();
        //设置参数
        updateWrapper.eq(ChickenReduce::getId, dto.getId());//设置更新条件
        updateWrapper.set(ChickenReduce::getAuditStatus, dto.getAuditStatus());//设置更新字段
        updateWrapper.set(ChickenReduce::getAuditRemark, dto.getAuditRemark());//设置更新字段
        updateWrapper.set(ChickenReduce::getAuditTime, new Date());//设置时间
        //审核成功后减少存栏库存
        LambdaQueryWrapper<ChickenReduceInfo> infoWrapper = new LambdaQueryWrapper<>();
        //查询子表
        infoWrapper.eq(ChickenReduceInfo::getOrderId,dto.getId());
        List<ChickenReduceInfo> infos = infoMapper.selectList(infoWrapper);
        //获取子表中的损耗数量
        infos.forEach(x->{
            //查询当前批次数据
            ChickenChickIn chick = chickInMapper.selectById(x.getHatchId());
            //如果损耗数量大于库存数量，抛异常
            if(x.getCockNum() > chick.getCockNum()){
                throw new RuntimeException("公鸡数量为"+x.getCockNum()+"行：库存量低于当前数量(公鸡)，请核实后再提交");
            }
            if(x.getHenNum() > chick.getHenNum()){
                throw new RuntimeException("母鸡数量为"+x.getHenNum()+"行：库存量低于当前数量(母鸡)，请核实后再提交");
            }
            //当前存栏减去损耗数量
            chick.setStockHen(chick.getStockHen() - x.getHenNum());
            chick.setStockCock(chick.getStockCock() - x.getCockNum());
            //执行chicken_chick_in表更新
            chickInMapper.updateById(chick);
        });

        //执行主表的更新方法
        baseMapper.update(updateWrapper);
    }
}
